<?php
/**
 * CrontabController.class.php
 * 轮训任务控制器
 * 
 * @author  王中艺 <wangzy_smile@qq.com>
 * @date    2017-08-18
 */

namespace Admin\Controller;
use \Think\Controller;

class CrontabController extends Controller {

    public $lockName;

    function __construct(){
        parent::__construct();

        //进程锁检测
        $this->lockName     = 'lock_admin_'.CONTROLLER_NAME.ACTION_NAME;
        if(S($this->lockName)){
            echo 'Process is exist!';
            exit;
        }
        S($this->lockName, 1, 3600 * 4);

        //超时设置
        set_time_limit(0);
    }

    /**
     * 电台定时上线
     * 每5分钟运行一次
     * 每次每项执行100条
     */
    function makeRadioOnline(){
        $makeOnline     = function($model, $remark = ''){
            $list   = $model->where('status = 2 and online_time <= %d', time())->limit(100)->select();
            foreach($list as $item){
                try{
                    $item['status'] = 1;
                    $model->save($item);
                }catch(\Exception $e){
                    write_log('./Log/crontab_error.log', $this->lockName.':'.$remark, [
                        'error'     => $e->getMessage(),
                        'item'  => $item
                    ]);
                }
            }

        };

        //幸福语录上线
        $makeOnline(D('Motto'), 'motto');
        //晨间电台上线
        $makeOnline(D('RadioMorning'), 'radio-morning');
        //晚间电台上线
        $makeOnline(D('RadioEvening'), 'radio-evening');
        //电台故事上线
        $makeOnline(D('RadioStory'), 'radio-story');
    }

    //析构函数
    function __destruct(){
        S($this->lockName, null);
    }
}
